/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CCPVCoalitionFormationViewer.java
 *
 * Created on Nov 6, 2009, 9:33:10 PM
 */
package CoalitionCirclePackage;

import CCPVConflictArrowDrawer.CCPVArrowDrawer;
import CCPVSimulationPackage.CCPVSimulation;
import CCPVSimulationPackage.CCPVSimulationIteration;
import GISPackage.Region;
import GUIUtilities.CoalitionUtilities;
import GUIUtilities.LabelManager;
import GUIUtilities.ListUtilities;
import GraphPackage.CCPVGraphMember;
import GraphPackage.CCPVGraphPanel;
import LabelPanelPackage.LabelPanel;
import SocialMatrixPackage.SocialMatrix;
import SwingAnimation.CCPVConflictOutcomeLabel;
import SwingAnimation.CCPVNoConflictLabel;
import SwingAnimation.ColorPulser;
import ccpv.FileManager;
import ccpv.RunTimeSettings;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import multiarray.MultiArray;
import solver.Results;

/**
 *
 * @author Heather
 */
public class CCPVCoalitionCircleViewerPanel extends javax.swing.JPanel
{

  /** Creates new form CCPVCoalitionFormationViewer */
  public CCPVCoalitionCircleViewerPanel()
  {
    initComponents();
    coalitionContainer.add(conflictLabelPanel);
    conflictLabelPanel.setSize(DEFAULT_SIZE);
    conflictLabelPanel.setPreferredSize(DEFAULT_SIZE);
    conflictLabelPanel.setOpaque(false);
    conflictLabelPanel.setLayout(null);
    // replace w/ robert's file reader, etc.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    setupDefaultCCPVSimulationIteration();
    ccv = new CoalitionCircleViewer(candidatePartitions.get(0), sm, population, power);
    setupCirclesAndLabelsContainers();
    setupLabels(ccv.getCoalitions());
    setupRightClickMenuOptions();
    setupRightClickMenuListeners();
    setSize(DEFAULT_SIZE);
    setPreferredSize(DEFAULT_SIZE);
    setupInfoLabels();
    coalitionContainer.add(arrowDrawer);
    arrowDrawer.setSize(DEFAULT_SIZE);
    arrowDrawer.setPreferredSize(DEFAULT_SIZE);
  }

  public CCPVCoalitionCircleViewerPanel(List<List<List<int[]>>> candidatePartitions, SocialMatrix sm, MultiArray<Integer> population, MultiArray<Double> power)
  {
    this.candidatePartitions = candidatePartitions;
    this.sm = sm;
    this.population = population;
    this.power = power;

    initComponents();
    coalitionContainer.add(conflictLabelPanel);
    conflictLabelPanel.setSize(DEFAULT_SIZE);
    conflictLabelPanel.setPreferredSize(DEFAULT_SIZE);
    conflictLabelPanel.setOpaque(false);
    conflictLabelPanel.setLayout(null);
    // replace w/ robert's file reader, etc.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    setupDefaultCCPVSimulationIteration();
    setupCirclesAndLabelsContainers();
    setupLabels(ccv.getCoalitions());
    setupRightClickMenuOptions();
    setupRightClickMenuListeners();
    setSize(DEFAULT_SIZE);
    setPreferredSize(DEFAULT_SIZE);
    setupInfoLabels();
    coalitionContainer.add(arrowDrawer);
    arrowDrawer.setSize(DEFAULT_SIZE);
    arrowDrawer.setPreferredSize(DEFAULT_SIZE);
  }

  public CCPVCoalitionCircleViewerPanel(String filename, Region r)
  {
    initComponents();
    coalitionContainer.add(conflictLabelPanel);
    conflictLabelPanel.setSize(DEFAULT_SIZE);
    conflictLabelPanel.setPreferredSize(DEFAULT_SIZE);
    conflictLabelPanel.setOpaque(false);
    conflictLabelPanel.setLayout(null);
    // replace w/ robert's file reader, etc.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    CCPVSimulationIteration si = new CCPVSimulationIteration(filename, r);
    power = si.getSimPop().getPowerFromPersonsAsDoubles();
    population = si.getSimPop().getPopulationFromPersonsAsInt();
    currentIteration = si;
    candidatePartitions = si.getAllPartitions();
    selectedIndex = 0;
    sm = si.getSM();
    ccv = new CoalitionCircleViewer(candidatePartitions.get(0), sm, population, power);
    setupCirclesAndLabelsContainers();
    setupLabels(ccv.getCoalitions());
    setupRightClickMenuOptions();
    setupRightClickMenuListeners();
    setSize(DEFAULT_SIZE);
    setPreferredSize(DEFAULT_SIZE);
    setupInfoLabels();
    coalitionContainer.add(arrowDrawer);
    arrowDrawer.setSize(DEFAULT_SIZE);
    arrowDrawer.setPreferredSize(DEFAULT_SIZE);
  }

  public CCPVCoalitionCircleViewerPanel(String filename)
  {
    initComponents();
    coalitionContainer.add(conflictLabelPanel);
    conflictLabelPanel.setSize(DEFAULT_SIZE);
    conflictLabelPanel.setPreferredSize(DEFAULT_SIZE);
    conflictLabelPanel.setOpaque(false);
    conflictLabelPanel.setLayout(null);
    setupDefaultSimIterationCaolitionCircleViewer(filename);
    setupCirclesAndLabelsContainers();
    setupLabels(ccv.getCoalitions());
    setupRightClickMenuOptions();
    setupRightClickMenuListeners();
    setSize(DEFAULT_SIZE);
    setPreferredSize(DEFAULT_SIZE);
    setupInfoLabels();
    coalitionContainer.add(arrowDrawer);
    arrowDrawer.setSize(DEFAULT_SIZE);
    arrowDrawer.setPreferredSize(DEFAULT_SIZE);
  }

  public void setupDefaultSimIterationCaolitionCircleViewer(String filename)
  {
    RunTimeSettings rt = FileManager.csvReader(filename);
    sm = new SocialMatrix(CoalitionUtilities.getAscriptiveTree(rt.ascriptive_names));
    Vector<int[]> allCombos = sm.getAllCombinations();
    population = new MultiArray<Integer>(sm.getDimensions());
    for (int[] i : allCombos)
    {
      population.setElementAtIndex(i, randGen.nextInt(1000) + 10);
    }

    power = new MultiArray<Double>(sm.getDimensions());
    for (int[] i : allCombos)
    {
      power.setElementAtIndex(i, randGen.nextDouble() * 10);
    }

    CCPVSimulationIteration si = new CCPVSimulationIteration(sm);
    theSim.addCCPVSimulationIteration(si);
    si.setRandomPartitions();
    candidatePartitions = si.getAllPartitions();
    ccv = new CoalitionCircleViewer(candidatePartitions.get(0), sm, population, power);
    currentIteration = si;
    selectedIndex = 0;
    sm = si.getSM();
    setupCirclesAndLabelsContainers();
    setupLabels(ccv.getCoalitions());
    setupRightClickMenuOptions();
    setupRightClickMenuListeners();
    setSize(DEFAULT_SIZE);
    setPreferredSize(DEFAULT_SIZE);
    setupInfoLabels();
    coalitionContainer.add(arrowDrawer);
  }

  private void setupInfoLabels()
  {
    LabelManager.resizeLabel(scaleLabel);
    scaleLabel.setLocation(DEFAULT_SCALE_LABEL_LOCATION);
    scaleLabel.setForeground(Color.RED);
    scaleLabel.setBackground(Color.white);
  }

  private void setupDefaultCCPVSimulationIteration()
  {
    theSim.addDefaultCCPVSimulationIteration();
    currentIteration = theSim.getNextIteration();
    candidatePartitions = currentIteration.getAllPartitions();
    selectedIndex = 0;

    sm = currentIteration.getSM();
    // making up populations here
    population = new MultiArray<Integer>(sm.getDimensions());
    Vector<int[]> allCombos = sm.getAllCombinations();

    for (int[] i : allCombos)
    {
      population.setElementAtIndex(i, randGen.nextInt(1000));
    }

    power = new MultiArray<Double>(sm.getDimensions());
    for (int[] i : allCombos)
    {
      power.setElementAtIndex(i, randGen.nextDouble() * 100);
    }
  }

  private void setupCirclesAndLabelsContainers()
  {
    coalitionContainer.add(ccv);
    ccv.setSize(coalitionContainer.getSize());
    ccv.setPreferredSize(coalitionContainer.getSize());
    lp.setBackground(Color.white);
    lp.setSize(labelsScrollPaneContainer.getSize());
    lp.setPreferredSize(labelsScrollPaneContainer.getSize());
    labelsContainer.setViewportView(lp);
    lp.setScaleTo(labelsContainer.getSize());
    System.out.println(labelsContainer.getSize());
  }

  private void setupLabels(List<List<int[]>> coalitions)
  {
    Vector<CCPVGroupCircle> allGroups = ccv.getAllGroupCircles();
    //List<List<int[]>> coalitions = ccv.getCoalitions();
    SocialMatrix sm = ccv.getSm();

    lp.removeAll();
    int coalitionIndex = 1;
    for (List<int[]> coalition : coalitions)
    {
      // add label for coalition
      JLabel coalitionLabel = new JLabel("Coalition " + coalitionIndex);
      coalitionLabel.setOpaque(true);
      coalitionLabel.setBackground(Color.white);
      Vector<CCPVGroupCircle> coalitionCircles = new Vector<CCPVGroupCircle>();
      Color defaultColor = ccv.getCoalitionColor(coalition);
      coalitionLabel.setBackground(defaultColor);
      lp.addLabel(coalitionLabel);

      for (int[] i : coalition)
      {
        // find which coalition i belongs to
        CCPVGroupCircle iCircle = null;
        for (CCPVGroupCircle c : allGroups)
        {
          if (c.containsGroups(i))
          {
            iCircle = c;
            coalitionCircles.add(c);
            break;
          }
        }

        // make a label for iCircle
        Vector<String> iStringVector = sm.convertIndexIntoStringVector(i);
        String iString = "";
        for (int j = 0; j < iStringVector.size() - 1; j++)
        {
          iString += iStringVector.get(j) + ", ";
        }
        iString += iStringVector.get(iStringVector.size() - 1);

        JLabel iLabel = new JLabel(iString);
        iLabel.setOpaque(true);
        iLabel.setBackground(Color.white);
        addListenersToGroupLabel(iLabel, iCircle);
        iLabel.setBackground(iCircle.defaultColor);
        lp.addLabel(iLabel);
      }

      addListenersToCoalitionLabel(coalitionLabel, coalitionCircles, defaultColor);
      coalitionIndex++;
      lp.addLabel(new JLabel(""));
    }
  }

  private void addListenersToCoalitionLabel(final JLabel l, final Vector<CCPVGroupCircle> coalition, final Color defaultColor)
  {
    l.addMouseListener(new java.awt.event.MouseAdapter()
    {

      public void mouseClicked(java.awt.event.MouseEvent evt)
      {
      }

      public void mouseEntered(java.awt.event.MouseEvent evt)
      {
        l.setBackground(getCoalitionLabelHighlight());
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        selected.clear();
        for (CCPVGroupCircle c : coalition)
        {
          selected.add(c);
        }
        getCoalitionContainer().repaint();
        ccv.setConflictFocusCoalition(ccv.getAllCoalitionCircles().get(coalition.get(0).coalition));
        if (conflictResults != null)
        {
          showConflict();
        }
      }

      public void mouseExited(java.awt.event.MouseEvent evt)
      {
        l.setBackground(defaultColor);
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        if (!isMenuOpen())
        {
          selected.clear();
        }
        getCoalitionContainer().repaint();
        previousConflictFocus = coalition.get(0).coalition;
      }

      public void mousePressed(java.awt.event.MouseEvent evt)
      {
        Point clickP = evt.getPoint();

        // menu options
        if (evt.getButton() != MouseEvent.BUTTON1)
        {
          getRightClickOptions().show(evt.getComponent(), clickP.x, clickP.y);
          menuOpen = true;
        }

        l.setBackground(getGroupLabelHighlight());
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        selected.clear();
        for (CCPVGroupCircle c : coalition)
        {
          selected.add(c);
        }
        ccv.setConflictFocusCoalition(ccv.getSelectedGroups().get(0));
        getCoalitionContainer().repaint();
      }

      public void mouseReleased(java.awt.event.MouseEvent evt)
      {
      }
    });
  }

  private void addListenersToGroupLabel(final JLabel l, final CCPVGroupCircle c)
  {
    l.addMouseListener(new java.awt.event.MouseAdapter()
    {

      public void mouseClicked(java.awt.event.MouseEvent evt)
      {
      }

      public void mouseEntered(java.awt.event.MouseEvent evt)
      {
        l.setBackground(getGroupLabelHighlight());
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        selected.clear();
        selected.add(c);
        getCoalitionContainer().repaint();
        System.out.println(c.population);
        ccv.setConflictFocusCoalition(ccv.getAllCoalitionCircles().get(c.coalition));
        if (conflictResults != null)
        {
          showConflict();
        }
      }

      public void mouseExited(java.awt.event.MouseEvent evt)
      {
        l.setBackground(c.defaultColor);
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        if (!isMenuOpen())
        {
          selected.clear();
        }
        getCoalitionContainer().repaint();
        previousConflictFocus = c.coalition;
      }

      public void mousePressed(java.awt.event.MouseEvent evt)
      {
        Point clickP = evt.getPoint();

        // menu options
        if (evt.getButton() != MouseEvent.BUTTON1)
        {
          getRightClickOptions().show(evt.getComponent(), clickP.x, clickP.y);
          menuOpen = true;
        }

        l.setBackground(getGroupLabelHighlight());
        getLabelsContainer().repaint();
        Vector<CCPVGroupCircle> selected = ccv.getSelectedGroups();
        selected.clear();
        selected.add(c);
        ccv.setConflictFocusCoalition(ccv.getSelectedGroups().get(0));
        getCoalitionContainer().repaint();
        System.out.println("menu showing.  size of selected: " + ccv.getSelectedGroups().size());
      }

      public void mouseReleased(java.awt.event.MouseEvent evt)
      {
      }
    });
  }

  private void setupRightClickMenuOptions()
  {
    //rightClickOptions.add(seeConflictsOption);
    rightClickOptions.add(changePopulationOrPowerOption);
  }

  private void setupRightClickMenuListeners()
  {
    /*
    seeConflictsOption.addActionListener(new java.awt.event.ActionListener()
    {

    public void actionPerformed(java.awt.event.ActionEvent evt)
    {
    showConflicts();
    menuOpen = false;
    }
    });*/

    changePopulationOrPowerOption.addActionListener(new java.awt.event.ActionListener()
    {

      public void actionPerformed(java.awt.event.ActionEvent evt)
      {
        getGroupVariablesDialog().setVisible(true);
        getGroupVariablesDialog().setSize(getGroupVariablesDialogSize());
        getGroupVariablesDialog().setPreferredSize(getGroupVariablesDialogSize());

        getGroupVariablesDialogSelectedGroupTextArea().setText(ccv.getSelectedGroupString());

        menuOpen = false;
        ccv.setAllProperColors();
        ccv.getSelectedGroups().clear();
        repaint();
      }
    });
  }

  private void showConflict()
  {
    //System.out.println("selected groups size: " + ccv.getSelectedGroups().size());
    //System.out.println("this is the conflict group: " + ccv.getConflictFocusCoalition());
    //System.out.println("showing conflicts?: " + ccv.isShowingConflicts());
    if (conflictResults.isConflict)
      System.out.println("THERE IS A CONFLICT");
    else
      System.out.println("THERE IS NO CONFLICT");
    ccv.setShowingConflicts(conflictResults.isConflict);
    ccv.setAllProperColors();
    if (!ccv.isShowingConflicts())
    {
      //getSeeConflictsOption().setText("See conflicts with this coalition");
      arrowDrawer.stopAnimation();
      conflictLabelPanel.removeAll();
      conflictLabelPulsers.clear();
      // add in a big label to say no conflict happened
      CCPVNoConflictLabel conflictL = new CCPVNoConflictLabel();
      LabelManager.centerLabelAtPoint(conflictL, new Point((int) (DEFAULT_SIZE.width / 2), (int) (DEFAULT_SIZE.height / 2)));
      ColorPulser conflictLPulser = new ColorPulser(conflictL);
      conflictLabelPanel.add(conflictL);
      conflictLPulser.setToMediumPhasing();
      conflictLPulser.startAnimation();
      conflictLabelPulsers.add(conflictLPulser);
    }
    else if (previousConflictFocus != ccv.getConflictFocusCoalition())
    {
      //getSeeConflictsOption().setText("Turn off conflicts");
      // setup the arrows
      boolean[][] winAndLoseMatrix = conflictResults.getWinners();
      float[][] thetas = conflictResults.getThetasF();
      arrowDrawer.clear();
      conflictLabelPanel.removeAll();
      conflictLabelPulsers.clear();
      int conflictFocus = ccv.getConflictFocusCoalition();
      CCPVCoalitionCircle conflictFocusCoalition = ccv.getAllCoalitionCircles().get(conflictFocus);
      Point conflictFocusPt = conflictFocusCoalition.centerLocation;
      List<CCPVCoalitionCircle> allCoalitionCircles = ccv.getAllCoalitionCircles();
      for (CCPVCoalitionCircle c : allCoalitionCircles)
      {
        // EVERYTHING IS RANDOM!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //System.out.println("EVERYTHING IS FUCKING RANDOM!!!");
        //int arrowWidth = randGen.nextInt(8);
        Point destinationPt = c.centerLocation;
        if (!c.equals(conflictFocusCoalition))
        {
          //int arrowWidth = (int) currentIteration.getConflictExpediture(conflictFocusCoalition.groups);
          int arrowWidth = (int) thetas[conflictFocusCoalition.coalition][c.coalition];
          //System.out.println("arrowWidth: " + arrowWidth);

          arrowDrawer.addArrow(conflictFocusPt, destinationPt, arrowWidth, Color.red, Color.white, true);
          arrowDrawer.addArrow(conflictFocusPt, destinationPt, arrowWidth, Color.red, Color.white, true, 1000);
          arrowDrawer.addArrow(conflictFocusPt, destinationPt, arrowWidth, Color.red, Color.white, true, 1300);
          arrowDrawer.addArrow(conflictFocusPt, destinationPt, arrowWidth, Color.red, Color.white, true, 1600);
          arrowDrawer.addArrow(conflictFocusPt, destinationPt, arrowWidth, Color.red, Color.white, true, 1900);

          // make a label for this conflict
          // for now we are just randomly generating this

          //boolean didWin = randGen.nextBoolean();
          boolean didWin = winAndLoseMatrix[conflictFocus][c.coalition];
          CCPVConflictOutcomeLabel conflictL = new CCPVConflictOutcomeLabel(didWin);
          LabelManager.centerLabelAtPoint(conflictL, destinationPt);
          System.out.println("%%%");
          System.out.println("destination pt: " + destinationPt);
          System.out.println("label pt: " + conflictL.getLocation());
          System.out.println("%%%");
          ColorPulser conflictLPulser;
          if (didWin)
          {
            conflictLPulser = new ColorPulser(conflictL);
          }
          else
          {
            conflictLPulser = new ColorPulser(conflictL, ColorPulser.PulseOptions.darken);
          }
          conflictLabelPanel.add(conflictL);
          conflictLPulser.setToSlowPhasing();
          conflictLPulser.startAnimation();
          conflictLabelPulsers.add(conflictLPulser);
        }
      }
      System.out.println("");
      arrowDrawer.scaleArrows(minArrowScale, maxArrowScale);
      arrowDrawer.setupAnimationSteps();
      arrowDrawer.startAnimation();
    }
    ccv.getSelectedGroups().clear();
    repaint();
  }

  private void stopShowingConflicts()
  {
    ccv.setShowingConflicts(false);
    arrowDrawer.stopAnimation();
    conflictLabelPanel.removeAll();
    conflictLabelPulsers.clear();
    conflictResults = null;
  }

  private void displaySelectedPartition()
  {
    if (chosenPartition != null)
    {
      ccv.setCoalitions(chosenPartition);
      ccv.clearAnimationScript();
      ccv.setupCoalitionFormationAnimationWithInitialPause(candidatePartitions.get(selectedIndex));
      ccv.startAnimation();
    }
    else
    {
      ccv.setCoalitions(candidatePartitions.get(selectedIndex));
    }
    setupLabels(candidatePartitions.get(selectedIndex));
    repaint();
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    groupVariablesDialog = new javax.swing.JDialog();
    jPanel1 = new javax.swing.JPanel();
    groupPowerTextField = new javax.swing.JTextField();
    groupPopulationTextField = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    groupVariablesDialogDoneButton = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    groupVariablesDialogSelectedGroupTextArea = new javax.swing.JTextArea();
    optionsDialog = new javax.swing.JDialog();
    jPanel3 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jLabel4 = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();
    altruismGraphDialog = new javax.swing.JDialog();
    altruismGraphContainer = new javax.swing.JPanel();
    powerGraphDialog = new javax.swing.JDialog();
    powerGraphContainer = new javax.swing.JPanel();
    coalitionContainer = new javax.swing.JPanel();
    labelsScrollPaneContainer = new javax.swing.JPanel();
    labelsContainer = new javax.swing.JScrollPane();
    CoalitionCircleViewerOptionsButton = new javax.swing.JButton();
    CoalitionCircleViewerModelProgressionButton = new javax.swing.JButton();
    CoalitionCircleViewerNextPartitionButton = new javax.swing.JButton();
    CoalitionCircleViewerPrevPartitionButton = new javax.swing.JButton();
    CoalitionCircleViewerScaleToggleButton = new javax.swing.JButton();
    CoalitionCircleToggleAnimationButton = new javax.swing.JButton();

    groupVariablesDialog.getContentPane().setLayout(null);

    jPanel1.setBackground(new java.awt.Color(255, 255, 204));
    jPanel1.setLayout(null);
    jPanel1.add(groupPowerTextField);
    groupPowerTextField.setBounds(20, 240, 460, 20);
    jPanel1.add(groupPopulationTextField);
    groupPopulationTextField.setBounds(20, 190, 460, 20);

    jLabel1.setFont(new java.awt.Font("Tahoma", 3, 11));
    jLabel1.setText("Power");
    jPanel1.add(jLabel1);
    jLabel1.setBounds(20, 220, 160, 14);

    jLabel2.setFont(new java.awt.Font("Tahoma", 3, 11));
    jLabel2.setText("Population");
    jPanel1.add(jLabel2);
    jLabel2.setBounds(20, 170, 160, 14);

    groupVariablesDialogDoneButton.setText("Done");
    jPanel1.add(groupVariablesDialogDoneButton);
    groupVariablesDialogDoneButton.setBounds(120, 280, 260, 50);

    groupVariablesDialogSelectedGroupTextArea.setColumns(20);
    groupVariablesDialogSelectedGroupTextArea.setEditable(false);
    groupVariablesDialogSelectedGroupTextArea.setRows(5);
    jScrollPane1.setViewportView(groupVariablesDialogSelectedGroupTextArea);

    jPanel1.add(jScrollPane1);
    jScrollPane1.setBounds(20, 20, 460, 140);

    groupVariablesDialog.getContentPane().add(jPanel1);
    jPanel1.setBounds(0, 0, 750, 530);

    jPanel3.setBackground(new java.awt.Color(204, 255, 255));
    jPanel3.setLayout(null);

    jButton1.setText("See changes in altruism");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });
    jPanel3.add(jButton1);
    jButton1.setBounds(10, 40, 230, 23);

    jLabel4.setFont(new java.awt.Font("Tahoma", 3, 14));
    jLabel4.setText("Options");
    jPanel3.add(jLabel4);
    jLabel4.setBounds(100, 0, 70, 30);

    jButton2.setText("See Agent Powers");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });
    jPanel3.add(jButton2);
    jButton2.setBounds(10, 70, 230, 23);

    optionsDialog.getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER);

    altruismGraphContainer.setBackground(new java.awt.Color(255, 204, 255));
    altruismGraphContainer.setLayout(null);
    altruismGraphDialog.getContentPane().add(altruismGraphContainer, java.awt.BorderLayout.CENTER);

    powerGraphContainer.setBackground(new java.awt.Color(204, 255, 255));
    powerGraphContainer.setLayout(null);
    powerGraphDialog.getContentPane().add(powerGraphContainer, java.awt.BorderLayout.CENTER);

    setBackground(new java.awt.Color(255, 255, 204));
    setLayout(null);

    coalitionContainer.setBackground(new java.awt.Color(255, 255, 255));
    coalitionContainer.setLayout(null);
    add(coalitionContainer);
    coalitionContainer.setBounds(10, 10, 600, 580);

    labelsScrollPaneContainer.setLayout(null);
    labelsScrollPaneContainer.add(labelsContainer);
    labelsContainer.setBounds(0, 0, 360, 580);

    add(labelsScrollPaneContainer);
    labelsScrollPaneContainer.setBounds(620, 10, 360, 580);

    CoalitionCircleViewerOptionsButton.setText("Options");
    CoalitionCircleViewerOptionsButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleViewerOptionsButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleViewerOptionsButton);
    CoalitionCircleViewerOptionsButton.setBounds(620, 620, 360, 30);

    CoalitionCircleViewerModelProgressionButton.setText("Pick this partition");
    CoalitionCircleViewerModelProgressionButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleViewerModelProgressionButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleViewerModelProgressionButton);
    CoalitionCircleViewerModelProgressionButton.setBounds(220, 590, 390, 60);

    CoalitionCircleViewerNextPartitionButton.setText("See next partition >>");
    CoalitionCircleViewerNextPartitionButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleViewerNextPartitionButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleViewerNextPartitionButton);
    CoalitionCircleViewerNextPartitionButton.setBounds(800, 590, 180, 30);

    CoalitionCircleViewerPrevPartitionButton.setText("<< See previous partition");
    CoalitionCircleViewerPrevPartitionButton.setEnabled(false);
    CoalitionCircleViewerPrevPartitionButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleViewerPrevPartitionButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleViewerPrevPartitionButton);
    CoalitionCircleViewerPrevPartitionButton.setBounds(620, 590, 180, 30);

    CoalitionCircleViewerScaleToggleButton.setText("Scale by POWER");
    CoalitionCircleViewerScaleToggleButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleViewerScaleToggleButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleViewerScaleToggleButton);
    CoalitionCircleViewerScaleToggleButton.setBounds(10, 590, 210, 30);

    CoalitionCircleToggleAnimationButton.setText("Turn animation OFF");
    CoalitionCircleToggleAnimationButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        CoalitionCircleToggleAnimationButtonActionPerformed(evt);
      }
    });
    add(CoalitionCircleToggleAnimationButton);
    CoalitionCircleToggleAnimationButton.setBounds(10, 620, 210, 30);
  }// </editor-fold>//GEN-END:initComponents

  private void CoalitionCircleViewerModelProgressionButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CoalitionCircleViewerModelProgressionButtonActionPerformed
  {//GEN-HEADEREND:event_CoalitionCircleViewerModelProgressionButtonActionPerformed
    // TODO add your handling code here:
    if (mode.equals(Modes.partitionSelection))
    {
      chosenPartition = candidatePartitions.get(selectedIndex);
      Results res = currentIteration.runConflict(chosenPartition);
      currentIteration.runCoherence();

      conflictResults = res;
      previousConflictFocus = -1;
      ccv.setConflictFocusCoalition(0);
      showConflict();
      mode = Modes.partitionFormation;

      CoalitionCircleViewerPrevPartitionButton.setEnabled(false);
      CoalitionCircleViewerNextPartitionButton.setEnabled(false);
      CoalitionCircleViewerModelProgressionButton.setText("Form new partitions");
    }
    else if (mode.equals(Modes.partitionFormation))
    {
      stopShowingConflicts();
      CCPVSimulationIteration si = new CCPVSimulationIteration(currentIteration);
      selectedIndex = 0;
      theSim.addCCPVSimulationIteration(si);
      currentIteration = si;
      candidatePartitions = si.getAllPartitions();
      CoalitionCircleViewerNextPartitionButton.setEnabled(true);

      displaySelectedPartition();
      mode = Modes.partitionSelection;

      CoalitionCircleViewerPrevPartitionButton.setEnabled(false);
      CoalitionCircleViewerNextPartitionButton.setEnabled(true);
      CoalitionCircleViewerModelProgressionButton.setText("Pick this partition");
    }
}//GEN-LAST:event_CoalitionCircleViewerModelProgressionButtonActionPerformed

  private void CoalitionCircleViewerNextPartitionButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CoalitionCircleViewerNextPartitionButtonActionPerformed
  {//GEN-HEADEREND:event_CoalitionCircleViewerNextPartitionButtonActionPerformed
    // TODO add your handling code here:
    selectedIndex++;
    displaySelectedPartition();
    if (selectedIndex >= candidatePartitions.size() - 1)
    {
      CoalitionCircleViewerNextPartitionButton.setEnabled(false);
    }
    if (selectedIndex > 0)
    {
      CoalitionCircleViewerPrevPartitionButton.setEnabled(true);
    }
}//GEN-LAST:event_CoalitionCircleViewerNextPartitionButtonActionPerformed

  private void CoalitionCircleViewerPrevPartitionButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CoalitionCircleViewerPrevPartitionButtonActionPerformed
  {//GEN-HEADEREND:event_CoalitionCircleViewerPrevPartitionButtonActionPerformed
    // TODO add your handling code here:
    selectedIndex--;
    displaySelectedPartition();
    if (selectedIndex <= 0)
    {
      CoalitionCircleViewerPrevPartitionButton.setEnabled(false);
    }
    if (selectedIndex < candidatePartitions.size() - 1)
    {
      CoalitionCircleViewerNextPartitionButton.setEnabled(true);
    }
}//GEN-LAST:event_CoalitionCircleViewerPrevPartitionButtonActionPerformed

  private void CoalitionCircleToggleAnimationButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CoalitionCircleToggleAnimationButtonActionPerformed
  {//GEN-HEADEREND:event_CoalitionCircleToggleAnimationButtonActionPerformed
    // TODO add your handling code here:
    isAnimated = !isAnimated;
    if (isAnimated)
    {
      CoalitionCircleToggleAnimationButton.setText("Turn animation OFF");
    }
    else
    {
      CoalitionCircleToggleAnimationButton.setText("Turn animation ON");
    }

    ccv.toggleAnimation();
  }//GEN-LAST:event_CoalitionCircleToggleAnimationButtonActionPerformed

  private void CoalitionCircleViewerScaleToggleButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_CoalitionCircleViewerScaleToggleButtonActionPerformed
  {//GEN-HEADEREND:event_CoalitionCircleViewerScaleToggleButtonActionPerformed
    // TODO add your handling code here:
    if (scale.equals(Scales.population))
    {
      scale = Scales.power;
      CoalitionCircleViewerScaleToggleButton.setText("Scale by POPULATION");
      scaleLabel.setText("Scaled by POWER");
      LabelManager.resizeLabel(scaleLabel);
      ccv.setScaling(CoalitionCircleViewer.SizeScalings.power);
    }
    else
    {
      scale = Scales.population;
      CoalitionCircleViewerScaleToggleButton.setText("Scale by POWER");
      scaleLabel.setText("Scaled by POPULATION");
      LabelManager.resizeLabel(scaleLabel);
      ccv.setScaling(CoalitionCircleViewer.SizeScalings.population);
    }
  }//GEN-LAST:event_CoalitionCircleViewerScaleToggleButtonActionPerformed

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    altruismGraphContainer.removeAll();

    // create a bar for each group
    Vector<CCPVGraphMember> graphMembers = new Vector<CCPVGraphMember>();
    HashMap<CCPVGraphMember, Double> values = new HashMap<CCPVGraphMember, Double>();
    for (CCPVGroupCircle group : ccv.getAllGroupCircles())
    {
      CCPVGraphMember member = new CCPVGraphMember(group.group);
      member.name = ListUtilities.getStringVectorString(sm.convertIndexIntoStringVector(group.group));
      member.valueType = CCPVGraphMember.ValueTypes.group;

      Double value = randGen.nextDouble() * 100;
      if (randGen.nextDouble() > 0.5)
        value *= -1;

      graphMembers.add(member);
      values.put(member, value);
    }

    CCPVGraphPanel altruismPanel = new CCPVGraphPanel(CCPVGraphPanel.GraphTypes.vertical, graphMembers);
    altruismPanel.setupBarValues(values);
    altruismGraphContainer.add(altruismPanel);

    Dimension altruismDialogSize = new Dimension(960, 580);
    altruismGraphDialog.setSize(altruismDialogSize);
    altruismGraphDialog.setPreferredSize(altruismDialogSize);
    altruismPanel.setSize(altruismDialogSize);
    altruismPanel.setPreferredSize(altruismDialogSize);

    altruismGraphDialog.setVisible(true);
  }//GEN-LAST:event_jButton1ActionPerformed

  private void CoalitionCircleViewerOptionsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CoalitionCircleViewerOptionsButtonActionPerformed
    // TODO add your handling code here:
    Dimension optionsSize = new Dimension(270, 150);
    optionsDialog.setSize(optionsSize);
    optionsDialog.setPreferredSize(optionsSize);
    optionsDialog.setVisible(true);
  }//GEN-LAST:event_CoalitionCircleViewerOptionsButtonActionPerformed

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton2ActionPerformed
  {//GEN-HEADEREND:event_jButton2ActionPerformed
    // TODO add your handling code here:
    powerGraphContainer.removeAll();

    // create a bar for each group
    MultiArray<Double> powers = currentIteration.getSimPop().getPowerFromPersonsAsDoubles();
    Vector<CCPVGraphMember> graphMembers = new Vector<CCPVGraphMember>();
    List<List<String>> graphMemberNames = new Vector<List<String>>();
    HashMap<CCPVGraphMember, Double> values = new HashMap<CCPVGraphMember, Double>();
    double maxValue = Double.MIN_VALUE;
    double minValue = Double.MAX_VALUE;
    for (CCPVGroupCircle group : ccv.getAllGroupCircles())
    {
      CCPVGraphMember member = new CCPVGraphMember(group.group);
      member.name = ListUtilities.getStringVectorString(sm.convertIndexIntoStringVector(group.group));
      member.valueType = CCPVGraphMember.ValueTypes.group;

      //Double value = randGen.nextDouble() * 100;
      //if (randGen.nextDouble() > 0.5)
      //  value *= -1;
      Double value = powers.getElementAtIndex(group.group);
      if (value < minValue)
        minValue = value;
      if (value > maxValue)
        maxValue = value;

      graphMembers.add(member);
      values.put(member, value);

      List<String> labelName = new Vector<String>();
      //labelName.add(ListUtilities.getStringVectorString(sm.convertIndexIntoStringVector(group.group)));
      //labelName.add("" + value);
      labelName.add("");
      graphMemberNames.add(labelName);
    }

    System.out.println("maxValue: " + maxValue);
    System.out.println("minValue: " + minValue);
    CCPVGraphPanel powerPanel = new CCPVGraphPanel(CCPVGraphPanel.GraphTypes.vertical, graphMembers, maxValue, 0, 0.1);
    powerPanel.setGraphTitle("Agent Powers");
    powerPanel.setupBarValues(values);
    powerPanel.setBarNames(graphMemberNames);
    powerGraphContainer.add(powerPanel);

    Dimension powerDialogSize = new Dimension(960, 580);
    powerGraphDialog.setSize(powerDialogSize);
    powerGraphDialog.setPreferredSize(powerDialogSize);
    powerPanel.setSize(powerDialogSize);
    powerPanel.setPreferredSize(powerDialogSize);

    powerGraphDialog.setVisible(true);
  }//GEN-LAST:event_jButton2ActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton CoalitionCircleToggleAnimationButton;
  private javax.swing.JButton CoalitionCircleViewerModelProgressionButton;
  private javax.swing.JButton CoalitionCircleViewerNextPartitionButton;
  private javax.swing.JButton CoalitionCircleViewerOptionsButton;
  private javax.swing.JButton CoalitionCircleViewerPrevPartitionButton;
  private javax.swing.JButton CoalitionCircleViewerScaleToggleButton;
  private javax.swing.JPanel altruismGraphContainer;
  private javax.swing.JDialog altruismGraphDialog;
  private javax.swing.JPanel coalitionContainer;
  private javax.swing.JTextField groupPopulationTextField;
  private javax.swing.JTextField groupPowerTextField;
  private javax.swing.JDialog groupVariablesDialog;
  private javax.swing.JButton groupVariablesDialogDoneButton;
  private javax.swing.JTextArea groupVariablesDialogSelectedGroupTextArea;
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JPanel jPanel1;
  private javax.swing.JPanel jPanel3;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JScrollPane labelsContainer;
  private javax.swing.JPanel labelsScrollPaneContainer;
  private javax.swing.JDialog optionsDialog;
  private javax.swing.JPanel powerGraphContainer;
  private javax.swing.JDialog powerGraphDialog;
  // End of variables declaration//GEN-END:variables
  // toggle variables

  private enum Modes
  {

    partitionSelection, partitionFormation
  };

  private enum Scales
  {

    power, population
  };
  private LabelPanel lp = new LabelPanel();
  private Color groupLabelHighlight = new Color(255, 255, 100, 255);
  private Color coalitionLabelHighlight = new Color(110, 250, 110, 255);
  private JPopupMenu rightClickOptions = new JPopupMenu();
  //private JMenuItem seeConflictsOption = new JMenuItem("See conflicts with this coalition");
  private JMenuItem changePopulationOrPowerOption = new JMenuItem("Change population or power");
  private boolean menuOpen = false;
  private Dimension groupVariablesDialogSize = new Dimension(525, 380);
  private static final Dimension DEFAULT_SIZE = new Dimension(1200, 1000);
  private Random randGen = new Random();
  private Scales scale = Scales.population;
  private Modes mode = Modes.partitionSelection;
  private boolean isAnimated = true;

  // variables for picking and setting up the partitions and animations
  private CoalitionCircleViewer ccv;
  //private Vector<CCPVSimulationIteration> allSimulationIterations = new Vector<CCPVSimulationIteration>();
  private CCPVSimulation theSim = new CCPVSimulation();
  private CCPVSimulationIteration currentIteration;
  private List<List<List<int[]>>> candidatePartitions = new Vector<List<List<int[]>>>();
  private List<List<int[]>> chosenPartition = null;
  // this indicates which circle viewer we see
  private int selectedIndex = 0;
  private MultiArray<Integer> population;
  private MultiArray<Double> power;
  private SocialMatrix sm;
  private JLabel scaleLabel = new JLabel("Scaled by POPULATION");
  private static Point DEFAULT_SCALE_LABEL_LOCATION = new Point(5, 5);
  private CCPVArrowDrawer arrowDrawer = new CCPVArrowDrawer();
  private int minArrowScale = 6;
  private int maxArrowScale = 30;
  private Vector<ColorPulser> conflictLabelPulsers = new Vector<ColorPulser>();
  private JPanel conflictLabelPanel = new JPanel();
  private Results conflictResults;
  private int previousConflictFocus = 0;

  /**
   * @return the CoalitionFormationViewerNextPartitionButton
   */
  public javax.swing.JButton getCoalitionFormationViewerNextPartitionButton()
  {
    return CoalitionCircleViewerNextPartitionButton;
  }

  /**
   * @return the CoalitionFormationViewerOptionsButton
   */
  public javax.swing.JButton getCoalitionFormationViewerOptionsButton()
  {
    return CoalitionCircleViewerOptionsButton;
  }

  /**
   * @return the CoalitionFormationViewerPickPartitionButton
   */
  public javax.swing.JButton getCoalitionFormationViewerPickPartitionButton()
  {
    return CoalitionCircleViewerModelProgressionButton;
  }

  /**
   * @return the CoalitionFormationViewerPrevPartitionButton
   */
  public javax.swing.JButton getCoalitionFormationViewerPrevPartitionButton()
  {
    return CoalitionCircleViewerPrevPartitionButton;
  }

  /**
   * @return the coalitionContainer
   */
  public javax.swing.JPanel getCoalitionContainer()
  {
    return coalitionContainer;
  }

  /**
   * @return the groupPopulationTextField
   */
  public javax.swing.JTextField getGroupPopulationTextField()
  {
    return groupPopulationTextField;
  }

  /**
   * @return the groupPowerTextField
   */
  public javax.swing.JTextField getGroupPowerTextField()
  {
    return groupPowerTextField;
  }

  /**
   * @return the groupVariablesDialog
   */
  public javax.swing.JDialog getGroupVariablesDialog()
  {
    return groupVariablesDialog;
  }

  /**
   * @return the groupVariablesDialogSelectedGroupTextArea
   */
  public javax.swing.JTextArea getGroupVariablesDialogSelectedGroupTextArea()
  {
    return groupVariablesDialogSelectedGroupTextArea;
  }

  /**
   * @return the jButton1
   */
  public javax.swing.JButton getJButton1()
  {
    return groupVariablesDialogDoneButton;
  }

  /**
   * @return the jLabel1
   */
  public javax.swing.JLabel getJLabel1()
  {
    return jLabel1;
  }

  /**
   * @return the jLabel2
   */
  public javax.swing.JLabel getJLabel2()
  {
    return jLabel2;
  }

  /**
   * @return the jPanel1
   */
  public javax.swing.JPanel getJPanel1()
  {
    return jPanel1;
  }

  /**
   * @return the jScrollPane1
   */
  public javax.swing.JScrollPane getJScrollPane1()
  {
    return jScrollPane1;
  }

  /**
   * @return the labelsContainer
   */
  public javax.swing.JScrollPane getLabelsContainer()
  {
    return labelsContainer;
  }

  /**
   * @return the labelsScrollPaneContainer
   */
  public javax.swing.JPanel getLabelsScrollPaneContainer()
  {
    return labelsScrollPaneContainer;
  }

  /**
   * @return the lp
   */
  public LabelPanel getLp()
  {
    return lp;
  }

  /**
   * @return the groupLabelHighlight
   */
  public Color getGroupLabelHighlight()
  {
    return groupLabelHighlight;
  }

  /**
   * @return the coalitionLabelHighlight
   */
  public Color getCoalitionLabelHighlight()
  {
    return coalitionLabelHighlight;
  }

  /**
   * @return the rightClickOptions
   */
  public JPopupMenu getRightClickOptions()
  {
    return rightClickOptions;
  }

  /**
   * @return the changePopulationOrPowerOption
   */
  public JMenuItem getChangePopulationOrPowerOption()
  {
    return changePopulationOrPowerOption;
  }

  /**
   * @return the menuOpen
   */
  public boolean isMenuOpen()
  {
    return menuOpen;
  }

  /**
   * @return the groupVariablesDialogSize
   */
  public Dimension getGroupVariablesDialogSize()
  {
    return groupVariablesDialogSize;
  }
}

